'use client'

import React, { createContext, useContext, useEffect, useState } from 'react'
import { type AuthUser } from '@/lib/auth-service'

interface AuthContextType {
  user: AuthUser | null
  loading: boolean
  login: (email: string, password: string) => Promise<{ success: boolean; error?: string }>
  register: (email: string, password: string, name: string) => Promise<{ success: boolean; error?: string }>
  logout: () => Promise<void>
  refreshUser: () => Promise<void>
  signOut: () => Promise<void> // 保持向后兼容
  getUserSessions: () => Promise<any[]>
  terminateSession: (sessionId: string) => Promise<boolean>
  terminateAllSessions: () => Promise<number>
}

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(null)
  const [loading, setLoading] = useState(true)

  // 获取当前用户信息
  const fetchUser = async () => {
    try {
      const response = await fetch('/api/auth/me', {
        credentials: 'include' // 确保发送 cookies
      })
      const result = await response.json()

      if (response.ok && result.success) {
        setUser(result.user)
      } else {
        setUser(null)
      }
    } catch (error) {
      console.error('获取用户信息失败:', error)
      setUser(null)
    } finally {
      setLoading(false)
    }
  }

  // 登录
  const login = async (email: string, password: string) => {
    try {
      const response = await fetch('/api/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include', // 确保接收 cookies
        body: JSON.stringify({ email, password }),
      })

      const result = await response.json()

      if (response.ok && result.success) {
        setUser(result.user)
        // 将token存储到localStorage，供API客户端使用
        if (result.token) {
          localStorage.setItem('auth-token', result.token)
        }
        return { success: true }
      } else {
        return { success: false, error: result.error || '登录失败' }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, error: '网络错误，请重试' }
    }
  }

  // 注册
  const register = async (email: string, password: string, name: string) => {
    try {
      const response = await fetch('/api/auth/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        credentials: 'include', // 确保接收 cookies
        body: JSON.stringify({ email, password, name }),
      })

      const result = await response.json()

      if (response.ok && result.success) {
        // 注册成功后自动登录
        const loginResult = await login(email, password)
        return loginResult
      } else {
        return { success: false, error: result.error || '注册失败' }
      }
    } catch (error) {
      console.error('注册失败:', error)
      return { success: false, error: '网络错误，请重试' }
    }
  }

  // 登出
  const logout = async () => {
    try {
      await fetch('/api/auth/logout', {
        method: 'POST',
        credentials: 'include', // 确保发送 cookies
      })
    } catch (error) {
      console.error('登出失败:', error)
    } finally {
      setUser(null)
      // 清理localStorage中的token
      localStorage.removeItem('auth-token')
    }
  }

  // 获取用户会话列表
  const getUserSessions = async (): Promise<any[]> => {
    if (!user) return []
    
    try {
      const token = localStorage.getItem('auth-token')
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      }
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }
      
      const response = await fetch('/api/auth/sessions', {
        headers,
        credentials: 'include'
      })
      const result = await response.json()
      
      if (response.ok && result.success) {
        return result.data || []
      }
      return []
    } catch (error) {
      console.error('获取会话列表失败:', error)
      return []
    }
  }

  // 终止指定会话
  const terminateSession = async (sessionId: string): Promise<boolean> => {
    if (!user) return false
    
    try {
      const token = localStorage.getItem('auth-token')
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      }
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }
      
      const response = await fetch(`/api/auth/sessions/${sessionId}`, {
        method: 'DELETE',
        headers,
        credentials: 'include'
      })
      const result = await response.json()
      
      return response.ok && result.success
    } catch (error) {
      console.error('终止会话失败:', error)
      return false
    }
  }

  // 终止所有会话（除了当前会话）
  const terminateAllSessions = async (): Promise<number> => {
    if (!user) return 0
    
    try {
      const token = localStorage.getItem('auth-token')
      const headers: Record<string, string> = {
        'Content-Type': 'application/json'
      }
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`
      }
      
      const response = await fetch('/api/auth/sessions/all', {
        method: 'DELETE',
        headers,
        credentials: 'include'
      })
      const result = await response.json()
      
      if (response.ok && result.success) {
        return result.data || 0
      }
      return 0
    } catch (error) {
      console.error('终止所有会话失败:', error)
      return 0
    }
  }

  // 刷新用户信息
  const refreshUser = async () => {
    await fetchUser()
  }

  useEffect(() => {
    fetchUser()
  }, [])

  const value = {
    user,
    loading,
    login,
    register,
    logout,
    refreshUser,
    signOut: logout, // 向后兼容
    getUserSessions,
    terminateSession,
    terminateAllSessions
  }

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  )
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider')
  }
  return context
}
